<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">校园二手交易平台管理系统</h3>
      </div>

      <el-form-item prop="studentId">
        <span class="svg-container">
          <i class="el-icon-user"></i>
        </span>
        <el-input
          ref="studentId"
          v-model="loginForm.studentId"
          placeholder="学号"
          name="studentId"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <i class="el-icon-lock"></i>
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          autocomplete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <i :class="passwordType === 'password' ? 'el-icon-view' : 'el-icon-hide'"></i>
        </span>
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        plain
      >登录</el-button>

      <div class="register-link">
        <router-link to="/register">
          <el-button type="info" round plain>注册新用户</el-button>
        </router-link>
      </div>
    </el-form>
  </div>
</template>

<script>
import authService from '@/services/auth.service'

export default {
  name: 'LoginPage',
  data() {
    const validateStudentId = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入学号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        studentId: '',
        password: ''
      },
      loginRules: {
        studentId: [{ required: true, trigger: 'blur', validator: validateStudentId }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    // 从localStorage恢复登录信息
    this.loginForm.studentId = localStorage.getItem('studentId') || ''
    this.loginForm.password = localStorage.getItem('password') || ''
  },
  methods: {
    showPwd() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password'
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          
          // 调用登录接口
          authService.login({
            studentId: this.loginForm.studentId,
            password: this.loginForm.password
          }).then(response => {
            console.log('登录响应:', response)
            
            if (response.code === 200) {
              // 登录成功，存储token和用户名
              this.$store.dispatch('user/setToken', {
                token: response.data,
                username: this.loginForm.studentId
              })
              
              // 保存登录信息到localStorage
              localStorage.setItem('studentId', this.loginForm.studentId)
              localStorage.setItem('password', this.loginForm.password)
              
              this.$message.success('登录成功')
              
              // 跳转到目标页面或首页
              this.$router.push({ path: this.redirect || '/' })
            } else {
              this.$message.error(response.message || '登录失败')
            }
          }).catch(error => {
            console.error('登录错误:', error)
            this.$message.error(error.message || '登录失败，请检查网络连接')
          }).finally(() => {
            this.loading = false
          })
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;

    .title-container {
      position: relative;
      text-align: center;
      margin-bottom: 40px;

      .title {
        font-size: 26px;
        color: #eee;
        margin: 0;
        font-weight: bold;
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: #889aa4;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: #889aa4;
      cursor: pointer;
      user-select: none;
    }

    ::v-deep .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0;
        -webkit-appearance: none;
        border-radius: 0;
        padding: 12px 5px 12px 15px;
        color: #fff;
        height: 47px;
        caret-color: #fff;

        &:-webkit-autofill {
          box-shadow: 0 0 0 1000px #283443 inset !important;
          -webkit-text-fill-color: #fff !important;
        }
      }
    }

    ::v-deep .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }

    .register-link {
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style> 